package com.lilosoft.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.lilosoft.core.utils.commons.StringUtils;

public class SimpleCORSFilter implements Filter {
	
	private final Log logger = LogFactory.getLog(this.getClass());
	
	public FilterConfig config;
	
	@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        
		String servletPath = request.getServletPath();
    	logger.info("===SimpleCORSFilter===");
        logger.info("request url : " + request.getRequestURI());
        logger.info("ServletPath : " + servletPath);
        logger.info("SessionId : " + request.getSession().getId());
        
		/***
		 * response().setHeader("Access-Control-Allow-Credentials", "true");
		 * response().setHeader("Access-Control-Allow-Origin", "fromeDomain.com");
		 * 这里fromeDomain.com 不能设置为 * 来允许全部，如果在 Credentials 是true 的情况下。因为浏览器会报错如下：
		 * A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. 
		 * Origin 'http://xxxxxxxxxx' is therefore not allowed access
		 * 所以只能乖乖的设置成客户端页面的 域名。
		 * 有一点需要注意，设置了widthCredentials为true的请求中会包含远程域的所有cookie，但这些cookie仍然遵循同源策略，所以你是访问不了这些cookie的。
		 */
		String allowOrigin = config.getInitParameter("allowOrigin");        //允许访问的域，*表示全部域
		if(!"*".equals(allowOrigin)) {	//指定域
			response.setHeader("Access-Control-Allow-Credentials", "true");
		}
		response.setHeader("Access-Control-Allow-Origin", StringUtils.isEmpty(allowOrigin)? "*" : allowOrigin);
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.addHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");
		chain.doFilter(servletRequest, servletResponse);
	}
	
	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;
    }

	@Override
    public void destroy() {
        this.config = null;
    }
}